package leetcode.jianzhioffer;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-10-31 18:12
 **/
public class JianZhiOffer47 {

    public int maxValue(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        //当在起点时dp[0][0] = grid[0][0]
        //在第一行dp[0][j] = dp[0][j-1] + grid[0][j]
        //在第一列dp[i][0] = dp[i-1][0] + grid[i][0]
        //非第一行第一列,dp[i][j] = max{dp[i-1][j],dp[i][j-1]} + grid[i][j];
        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 && j == 0) {
                    dp[i][j] = grid[i][j];
                } else if (i == 0) {
                    dp[0][j] = dp[0][j - 1] + grid[0][j];
                } else if (j == 0) {
                    dp[i][0] = dp[i - 1][0] + grid[i][0];
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
                }
            }
        }
        return dp[m - 1][n - 1];
    }

}
